package com.wn.network.interceptor

import com.blankj.utilcode.util.LogUtils
import com.wn.network.constant.KEY_SAVE_USER_LOGIN
import com.wn.network.constant.KEY_SAVE_USER_REGISTER
import com.wn.network.constant.KEY_SET_COOKIE
import com.wn.network.utils.CookiesManager
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton

/**
 * @Author: wn
 * @Date: 2024/7/29 16:29
 * @Description: Cookies拦截器 -- MMKV 保存 Cookie
 * 请求响应中自带 : Header:{Set-Cookie = xx;xx;xx;xx}
 */
@Singleton
class CookiesInterceptor @Inject constructor(private val cookiesManager: CookiesManager) :
  Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    val newBuilder = request.newBuilder()

    val response = chain.proceed(newBuilder.build())

    /**
     * URL                       host()
     * http://android.com/       "android.com"
     */
    val url = request.url.toString()

    // 请求响应中自带 : Header:{Set-Cookie = xx;xx;xx;xx}, 登陆 注册 接口  --> save cookie
    if ((url.contains(KEY_SAVE_USER_LOGIN) || url.contains(KEY_SAVE_USER_REGISTER))
      && response.headers(KEY_SET_COOKIE).isNotEmpty()
    ) {
      val cookies = response.headers(KEY_SET_COOKIE)
      val cookiesStr = cookiesManager.encodeCookie(cookies)
      cookiesManager.saveCookies(cookiesStr)
      LogUtils.e("CookiesInterceptor:cookies:$cookies")
    }
    return response
  }
}